package cc.vicp.djx314.starfood.web.security;

import java.util.Collection;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

/**
 * 要本机登陆和账号密码两个条件同时符合才能登陆的用户组
 * @author 水山清风
 *
 */
public class IpAddressVoter implements AccessDecisionVoter<Object> {
	/**
	 * 用户组前缀
	 */
	public static final String IP_PREFIX = "IP_";
	/**
	 * 用户组名称
	 */
	public static final String IP_LOCAL_HOST = "IP_LOCAL_HOST";

	@Override
	public boolean supports(ConfigAttribute attribute) {
		boolean aa = attribute.getAttribute() != null && attribute.getAttribute().startsWith(IP_PREFIX);
		return aa;
	}

	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}

	/**
	 * 返回权限配置
	 * @param authentication
	 * @return
	 */
	Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
		return authentication.getAuthorities();
	}

	@Override
	public int vote(Authentication authentication, Object arg1, Collection<ConfigAttribute> configList) {
		if (!(authentication.getDetails() instanceof WebAuthenticationDetails)) {
			return ACCESS_DENIED;
		}
		Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);
		WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
		String address = details.getRemoteAddress();
		int result = ACCESS_ABSTAIN;
		for (ConfigAttribute config : configList) {
			result = ACCESS_DENIED;
			if(IP_LOCAL_HOST.equals(config.getAttribute())){
				if (address.equals("127.0.0.1") || address.equals("0:0:0:0:0:0:0:1")) {
					// Attempt to find a matching granted authority
					for (GrantedAuthority authority : authorities) {
						if (config.getAttribute().equals(authority.getAuthority())) {
							return ACCESS_GRANTED;
						}
					}
				}
			}
		}
		return result;
	}
}
